#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import subprocess


def run_prg(cmd):
    cmd_result = subprocess.Popen(cmd,
                                  shell = True,
                                  stderr = subprocess.STDOUT,
                                  stdout = subprocess.PIPE).communicate()[0]
    return cmd_result


def get_git_version(base_path):
    ver_last_commit = run_prg("git show").split()
    current_ver_commit = ver_last_commit[1].decode("utf-8")
    version = current_ver_commit

    for lt in run_prg("git tag").split():
        v_show = run_prg("git show %s" % lt.decode("utf-8")).decode("utf-8")
        v_commit = v_show.split()
        v_commit = v_commit[v_commit.index("commit") + 1]
        if v_commit == current_ver_commit:
            version = lt.decode("utf-8")
            break
    else:
        version = current_ver_commit[0:8]

    diff = run_prg("git diff")
    if diff:
        print("Warning:Git Repository Not Clean!")
        version = "%s_DirtyCode" % version
    return version


def get_main_dir():
    """Return the script directory - whether we're frozen or not."""
    return os.path.abspath(os.path.dirname(sys.argv[0]))


def main(argv):
    if "".join(argv) == "clean":
        run_prg("git checkout prg_version.h")
        return
    base_dir = get_main_dir()
    git_version = get_git_version(base_dir)
    f_version_h = open(base_dir + "/prg_version.h", "w")
    v_data_time_str = time.strftime('%Y%m%d',time.localtime(time.time()))
    version = "".join(argv) + "_" + git_version + "_" + v_data_time_str

    print("%s"% version)
    f_version_h.writelines("//" + version + "\n")
    f_version_h.writelines("#ifndef _PRG_VERSION_H_\n")
    f_version_h.writelines("#define _PRG_VERSION_H_\n")
    f_version_h.writelines("#define PRG_VERSION \"%s\\r\\n\"\n" % version)
    f_version_h.writelines("#endif\n")
    f_version_h.close()

     
    version = git_version + "_" + v_data_time_str
    f_version_h = open(base_dir + "/version", "w")
    f_version_h.writelines("VERSION=%s\n" % version)
    f_version_h.close()

if __name__ == '__main__':
    main(sys.argv[1:])
